#include "FontTab.h"
#include "../Util/Util.h"
#include "Config.h"
#include "../debug_new.h"

#include "XMLParser.h"

#define FONTTABLEFILE L"FontTab.xml"

CFontTab::CFontTab(void)
{
}

CFontTab::~CFontTab(void)
{
	map<wstring,CFont*>::iterator i,iEnd;
	i = m_mapItems.begin();
	iEnd = m_mapItems.end();

	CFont *pFont;

	for(; i != iEnd; i++)
	{
		pFont = (CFont*)(*i).second;
		delete pFont;
	}
	m_mapItems.clear();
}

CFontTab* CFontTab::g_pInstance = NULL;

CFontTab* CFontTab::GetInstance()
{
	if(NULL == g_pInstance)
	{
		g_pInstance = new CFontTab();

		if(!g_pInstance->InitFontMap())
		{
			delete g_pInstance;
			g_pInstance = NULL;
		}
	}

	return g_pInstance;
}

BOOL CFontTab::InitFontMap()
{
	CXMLParser xml;

#ifdef XML_FROM_FILE

	wstring strPath = CUtil::GetCurrentDirectory();
	strPath += L"\\Config\\";
	strPath += CConfig::GetInstance()->GetSkin();
	strPath += L"\\";
	strPath += FONTTABLEFILE;

	if(!xml.Load(strPath))
	{
		return FALSE;
	}
#else

	//wstring strPath = CUtil::GetCurrentDirectory();
	//strPath += L"\\Config\\";
	//strPath += CConfig::GetInstance()->GetSkin();
	//strPath += L"\\";
	//strPath += FONTTABLEFILE;

	if(!CUtil::InitResXML(xml,wstring(FONTTABLEFILE),L"XML"))
	{
		return FALSE;
	}

#endif

	m_mapItems.clear();

	CFont *pFont;

	LOGFONT logfont;

	while(xml.FindChildElem())
	{
		pFont = new CFont;

		memset (&logfont, 0, sizeof (logfont));
		logfont.lfHeight = _wtoi(xml.GetChildAttrib(L"HEIGHT").c_str());
		logfont.lfWidth = _wtoi(xml.GetChildAttrib(L"WIDTH").c_str());
		logfont.lfWeight = _wtoi(xml.GetChildAttrib(L"WEIGHT").c_str());
		logfont.lfCharSet = _wtoi(xml.GetChildAttrib(L"CHARSET").c_str());
		_tcsncpy (logfont.lfFaceName, xml.GetChildAttrib(L"FACE").c_str(), LF_FACESIZE);
		logfont.lfFaceName[LF_FACESIZE-1] = TEXT('\0');

		logfont.lfEscapement = 0;
		logfont.lfOrientation = 0;
		logfont.lfItalic = FALSE;
		logfont.lfUnderline = FALSE;
		logfont.lfStrikeOut = FALSE;
		logfont.lfOutPrecision = OUT_DEFAULT_PRECIS;
		logfont.lfClipPrecision = CLIP_DEFAULT_PRECIS;
		logfont.lfQuality = CLEARTYPE_QUALITY;
		logfont.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;

		pFont->CreateFontIndirect(&logfont);

		m_mapItems.insert(map<wstring,CFont*>::value_type(xml.GetChildTagName(),pFont));
	}

	return TRUE;
}

CFont* CFontTab::GetFont(wstring strKey)
{
	if(NULL == g_pInstance)
	{
		return NULL;
	}

	return m_mapItems[strKey];
}

